package com.collect.cameroon.zhiScene.zhiPublic;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Instrumentation;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;

import androidx.annotation.RequiresApi;

import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.collect.cameroon.R;
import com.collect.cameroon.zhiBase.BaseActivity;
import com.collect.cameroon.zhiGlobal.zhiAppSettings.ZHIProjectRouter;
import com.collect.cameroon.zhiScene.zhiWidget.zhiNavigationBar.ZHINavigationBar;
import com.collect.cameroon.zhiUtils.MyLogger;

import butterknife.BindView;

@SuppressLint("NonConstantResourceId")
@Route(path = ZHIProjectRouter.ZHI_Public_Webview)
public class ZHIWebViewActivity extends BaseActivity {

    @BindView(R.id.navigationBar)
    ZHINavigationBar navigationBar;

    @Autowired
    public String title;
    @Autowired
    public String url;
    @Autowired
    public String html;

    @Override
    protected void initInjector() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_webview;
    }


    public void actionKey(final int keyCode) {
        new Thread() {
            public void run() {
                try {
                    Instrumentation inst = new Instrumentation();
                    inst.sendKeyDownUpSync(keyCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled"})
    @Override
    protected void initView() {

        navigationBar.hideRight().setCenterText(title).setBarClickListener(new ZHINavigationBar.OnNavigationBarClickListener() {
            @Override
            public void onNavigationBarLeftClick(View v) {
                actionKey(KeyEvent.KEYCODE_BACK);
            }

            @Override
            public void onNavigationBarRightClick(View v) {
            }
        });
        navigationBar.setLeftImgage(R.drawable.ic_91);
        navigationBar.showLeft();

        final WebView webView = findViewById(R.id.webView);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setSupportZoom(true);
        settings.setTextZoom(100);
        settings.setUseWideViewPort(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(false);//设置自适应
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        webView.addJavascriptInterface(new JavascriptInterface(), "android");

        webView.setWebViewClient(new WebViewClient() {//页面监听
            @Override
            public void onLoadResource(WebView view, String url) {

                super.onLoadResource(view, url);
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, WebResourceRequest request) {
                return shouldOverrideUrlLoading(view, request.getUrl().toString());
            }

            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, String url) {
                MyLogger.e("TAG", "shouldOverrideUrlLoading:" + url);
                return false;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                final SslErrorHandler mHandler;
                mHandler = handler;
                AlertDialog.Builder builder = new AlertDialog.Builder(ZHIWebViewActivity.this);
                builder.setMessage("SSL certificate verification failed");
                builder.setPositiveButton("Continue", (dialog, which) -> mHandler.proceed());
                builder.setNegativeButton("Cancel", (dialog, which) -> mHandler.cancel());
                builder.setOnKeyListener((dialog, keyCode, event) -> {
                    if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                        mHandler.cancel();
                        dialog.dismiss();
                        return true;
                    }
                    return false;
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });


        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
                progressBar.setProgress(newProgress);
                if (newProgress == 100) {
                    progressBar.setVisibility(View.GONE);
                    webView.setVisibility(View.VISIBLE);
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                }
                super.onProgressChanged(view, newProgress);
            }
        });

        webView.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
                return true;
            }
            return false;
        });

        if (!TextUtils.isEmpty(html)) {
            webView.loadDataWithBaseURL(url, html, "text/html", "utf-8", url);
        } else {
            webView.loadUrl(url);
        }
    }

    public static class JavascriptInterface {
        public JavascriptInterface() {
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

}
